import {
  loginByUsername,
  logout,
  getUserInfo,
  searchApproveList,
  searchApproveListbian
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken,
  getRefreshToken,
  setRefreshToken,
  removeRefreshToken
} from '@/utils/auth'
import utils from '@/utils/getUrl'
import axios from 'axios'
import Cookies from 'js-cookie'
const user = {
  state: {
    leftNum: -270,
    user: '',
    status: '',
    code: '',
    token: getToken(),
    refreshToken: getRefreshToken(),
    name: '',
    org_name: '',
    avatar: '',
    introduction: '',
    userid: '',
    roles: '',
    setting: {
      articlePlatform: []
    },
    selectOuinfoId: '11',
    selectOrgId: '11',
    rootOrgId: '11',
    projectId: '',
    memberType: '',
    isChildMenuShow: false
  },

  mutations: {
    SET_SIDEBAR_MENU: (state, leftNum) => {
      state.leftNum = leftNum
    },
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_SELECTOUINFOID: (state, selectOuinfoId) => {
      state.selectOuinfoId = selectOuinfoId
    },
    SET_SELECTROLEORGID: (state, selectRoleOrgId) => {
      state.selectRoleOrgId = selectRoleOrgId
    },
    SET_SELECTROLEORGID_BYORGID: (state, selectRoleOrgIdByOrg) => {
      state.selectRoleOrgIdByOrg = selectRoleOrgIdByOrg
    },
    SET_SELECTROLEORGID_BYORGID_PT: (state, selectRoleOrgIdByOrgPt) => {
      state.selectRoleOrgIdByOrgPt = selectRoleOrgIdByOrgPt
    },
    SET_SELECTROLEORGID_BYROLEORGID: (state, selectRoleOrgIdByRoleOrg) => {
      state.selectRoleOrgIdByRoleOrg = selectRoleOrgIdByRoleOrg
    },
    SET_SELECTCOPYROLEORGID_BYORGID: (state, selectCopyRoleOrgIdByOrg) => {
      state.selectCopyRoleOrgIdByOrg = selectCopyRoleOrgIdByOrg
    },
    SET_SELECTCOPYROLEORGID_BYORGID_PT: (state, selectCopyRoleOrgIdByOrgPt) => {
      state.selectCopyRoleOrgIdByOrgPt = selectCopyRoleOrgIdByOrgPt
    },
    SET_SELECTOUINFONAME: (state, selectOuinfoName) => {
      state.selectOuinfoName = selectOuinfoName
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ORGNAME: (state, org_name) => {
      state.org_name = org_name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },

    SET_USERID: (state, userid) => {
      state.userid = userid
    },
    SET_ORGID: (state, orgId) => {
      state.orgId = orgId
    },

    SET_ROLES: (state, roles) => {
      state.roles = roles
    },

    SET_CORPID: (state, corpId) => {
      state.corpId = corpId
    },

    SET_CORPNAME: (state, corpName) => {
      state.corpName = corpName
    },

    SET_CORPCODE: (state, corpCode) => {
      state.corpCode = corpCode
    },

    SET_ISCHILDMENUSHOW: (state, isShow) => {
      state.isChildMenuShow = isShow
    },
    SET_PROJECTID: (state, id) => {
      state.projectId = id
    },
    SET_MEMBERTYPE: (state, memberType) => {
      state.memberType = memberType
    }
  },

  actions: {
    // 查询审批人员列表
    SearchApproveList({ commit }, postselectinfo) {
      return new Promise((resolve, reject) => {
        searchApproveList(postselectinfo).then(response => {
          resolve(response.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 待编查询下一审核人
    SearchApproveListbian({ commit }, postselectinfo) {
      return new Promise((resolve, reject) => {
        searchApproveListbian(postselectinfo).then(response => {
          resolve(response.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(res => {
          console.log('loginByUsername:', res)
          // 登录成功后将token存储在vuex cookie之中
          const data = res.data
          commit('SET_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          setToken(data.access_token)
          setRefreshToken(data.refresh_token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // CASLoginByUsername({ commit }, userInfo) {
    //   return new Promise((resolve, reject) => {
    //     const code = utils.getUrlKey('code')
    //     axios.post(`${process.env.CERTIFICATION_API}/oauth2.0/accessToken?grant_type=authorization_code&client_id=http://100001&client_secret=100001abcdeft&redirect_uri=${process.env.WEB_URL}&code=` + code).then((res) => {
    //       const tokenString = res.data
    //       const tokenStringItem = tokenString.split('&')
    //       for (let k in tokenStringItem) {
    //         if (tokenStringItem[k].split('=')[0] === 'access_token') {
    //           commit('SET_TOKEN', tokenStringItem[k].split('=')[1])
    //           setToken(tokenStringItem[k].split('=')[1])
    //         } else if (tokenStringItem[k].split('=')[0] === 'refresh_token') {
    //           commit('SET_REFRESH_TOKEN', tokenStringItem[k].split('=')[1])
    //           setRefreshToken(tokenStringItem[k].split('=')[1])
    //         }
    //       }
    //       resolve()
    //     }).catch((e) => {
    //       console.log(e)
    //     })
    //   })
    // },

    RefreshStoreToken({ commit, state }, newToken) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', newToken)
        setToken(newToken)
        resolve()
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(response => {
          if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('error')
          }
          const info = response.data.data
          if (!info) {
            reject('error')
          }
          // 用户ID
          commit('SET_USERID', info.id)
          // 用户昵称
          commit('SET_NAME', info.name)
          // 角色
          commit('SET_ROLES', '')
          // 用户公司ID
          commit('SET_CORPID', info.corpId)
          // 用户公司名称
          commit('SET_CORPNAME', info.corpName)
          // 用户公司编码
          commit('SET_CORPCODE', info.corpCode)
          // 用户组织机构ID
          commit('SET_ORGID', info.org_id)
          // 组织结构
          commit('SET_ORGNAME', info.org_name)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_REFRESH_TOKEN', '')
            commit('SET_ROLES', '')
            removeToken()
            removeRefreshToken()
            resolve()
          })
          .catch(error => {
            commit('SET_TOKEN', '')
            commit('SET_REFRESH_TOKEN', '')
            commit('SET_ROLES', '')
            removeToken()
            removeRefreshToken()
            resolve(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit, state }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '')
        commit('SET_ROLES', '')
        removeToken()
        removeRefreshToken()
        Cookies.remove('navVal')
        Cookies.remove('navNum')
        // Cookies.remove('dropNum')
        // Cookies.remove('dropVal')
        resolve()
      })
    }

    // 动态修改权限
    // ChangeRole({ commit }, role) {
    //   return new Promise(resolve => {
    //     commit('SET_TOKEN', role)
    //     setToken(role)
    //     getUserInfo(role).then(response => {
    //       const data = response.data
    //       commit('SET_ROLES', data.role)
    //       commit('SET_NAME', data.name)
    //       commit('SET_AVATAR', data.avatar)
    //       commit('SET_INTRODUCTION', data.introduction)
    //       resolve()
    //     })
    //   })
    // }
  }
}

export default user
